#include "minimapeditdialog.h"
#include "ui_minimapeditdialog.h"
#include <QFileDialog>
#include <QDebug>

MiniMapEditDialog::MiniMapEditDialog(PropData *minimapToEdit, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MiniMapEditDialog)
{
    ui->setupUi(this);
    window()->layout()->setSizeConstraint(QLayout::SetFixedSize);

    if (minimapToEdit != 0)
    {
        minimap = minimapToEdit;
        ui->tlLatDoubleSpinBox->setValue(minimapToEdit->propCoords[0].latitude);
        ui->tlLonDoubleSpinBox->setValue(minimapToEdit->propCoords[0].longitude);
        ui->lrLatDoubleSpinBox->setValue(minimapToEdit->propCoords[1].latitude);
        ui->lrLonDoubleSpinBox->setValue(minimapToEdit->propCoords[1].longitude);
        ui->mapImgLineEdit->setText(minimapToEdit->pic[0]->first);
        // possibly try to display image
        QFileInfo finfo(minimapToEdit->pic[0]->first);
        if (!finfo.exists())
        {
            qDebug() << "first: " + minimapToEdit->pic[0]->first;
            qDebug() << minimapToEdit->pic[0]->second;
            finfo.setFile(minimapToEdit->pic[0]->first + ".lnk");
            ui->imgTextBrowser->setText("<img src=\"" + finfo.symLinkTarget() + "\"width=\"245\" />");
        }
        else
        {
            ui->imgTextBrowser->setText("<img src=\"" + minimapToEdit->pic[0]->first + "\" width=\"245\" />");
        }
    }
    else
    {
        minimap = new PropData;
    }
}

MiniMapEditDialog::~MiniMapEditDialog()
{
    delete ui;
}

void MiniMapEditDialog::accept()
{
    if (ui->mapImgLineEdit->text() == "")
    {
        QPalette pal(ui->mapImgLineEdit->palette());
        pal.setColor(QPalette::Base, Qt::yellow);
        ui->mapImgLineEdit->setPalette(pal);
        return;
    }

    minimap->propCoords[0].latitude = ui->tlLatDoubleSpinBox->value();
    minimap->propCoords[0].longitude = ui->tlLonDoubleSpinBox->value();
    minimap->propCoords[1].latitude = ui->lrLatDoubleSpinBox->value();
    minimap->propCoords[1].longitude = ui->lrLonDoubleSpinBox->value();
    std::vector<QString> p;
    p.push_back(ui->mapImgLineEdit->text());
    minimap->addPic(p);
    minimap->changePropName("Minimap");

    emit newMinimapInfo(minimap);
    QDialog::accept();
}

void MiniMapEditDialog::on_mapImgBrowsePushButton_clicked()
{
    QString fname = QFileDialog::getOpenFileName(this, "Open Image", QString(), "Image (*.png *.jpg)");
    ui->mapImgLineEdit->setText(fname);
    ui->imgTextBrowser->setText("<img src=\"" + fname + "\" width=\"245\" />");
}

void MiniMapEditDialog::on_buttonBox_accepted()
{
    accept();
}

void MiniMapEditDialog::on_buttonBox_rejected()
{
    reject();
}
